import { Application, codo } from "egg";
import WeWorkBaseService from "./WeWorkBaseService";
import { WeWork } from "./type";

/**
 * 第三方应用调用，suite app 相关接口集合。全都使用suiteAccessToken
 */
export default class SuiteApp extends WeWorkBaseService {
	constructor(
		protected config: codo.WeWork.IWeWorkConfig,
		private suiteAccessToken: string,
		protected app: Application
	) {
		super(config, app);
	}

	/**
	 * 第三方应用
	 * - 获取预授权码，注意传入的accessToken是第三方应用凭证，suiteAccessToken
	 * - https://developer.work.weixin.qq.com/document/path/90601
	 */
	async getPreAuthCode() {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token=${this.suiteAccessToken}`;
		const r = await this.curl<WeWork.IGetPreAuthCodeResponse>(url, {
			method: "GET",
			dataType: "json",
			contentType: "json",
			timeout: [30000, 30000],
		});
		const res = r.data;

		if (res.errcode && res.errcode !== 0) {
			this.app.logger.error(`获取预授权码异常 %j`, res);
			throw new Error(res.errcode + (res.errmsg || ""));
		}

		return res;
	}

	/**
	 * 第三方应用
	 * - 设置授权配置
	 * - https://developer.work.weixin.qq.com/document/path/90602
	 * @param {0 | 1} auth_type 授权类型：0 正式授权， 1 测试授权。 默认值为0。
	 */
	async setSessionInfo(pre_auth_code: string, auth_type: 0 | 1) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/service/set_session_info?suite_access_token=${this.suiteAccessToken}`;
		const body = {
			pre_auth_code,
			session_info: {
				auth_type: auth_type,
			},
		};

		const r = await this.curl<WeWork.IResponse>(url, {
			method: "POST",
			dataType: "json",
			contentType: "json",
			data: body,
			timeout: [30000, 30000],
		});
		if (r.data.errcode && r.data.errcode !== 0) {
			this.app.logger.error(`设置授权配置异常 %j`, r.data);
			throw new Error(r.data.errcode + (r.data.errmsg || ""));
		}
		return true;
	}

	/**
	 * 获取企业永久授权码，与自建应用类似，通过code换取企业永久授权码
	 * - code来源于前端redirect_uri或者企业授权应用时的授权回调
	 * - https://developer.work.weixin.qq.com/document/path/90603
	 */
	async getPermanentCode(auth_code: string) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token=${this.suiteAccessToken}`;
		const body = {
			auth_code,
		};

		const r = await this.curl<WeWork.IGetPermanentCodeResponse>(url, {
			method: "POST",
			dataType: "json",
			contentType: "json",
			data: body,
			timeout: [30000, 30000],
		});

		if (r.data.errcode && r.data.errcode !== 0) {
			this.app.logger.error(`获取企业永久授权码出错 %j`, r.data);
			throw new Error(r.data.errcode + (r.data.errmsg || ""));
		}
		return r.data;
	}

	/**
	 * 第三方应用
	 * - 获取企业授权信息
	 *
	 */
	async getAuthInfo(auth_corpid: string, permanent_code: string) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/service/get_auth_info?suite_access_token=${this.suiteAccessToken}`;

		const body = {
			auth_corpid,
			permanent_code,
		};

		const r = await this.curl<WeWork.ICorpAuthInfo>(url, {
			method: "POST",
			dataType: "json",
			contentType: "json",
			data: body,
			timeout: [30000, 30000],
		});

		if (r.data.errcode && r.data.errcode !== 0) {
			this.app.logger.error(`获取企业授权信息出错 %j`, r.data);
			throw new Error(r.data.errcode + (r.data.errmsg || ""));
		}
		return r.data;
	}

	/**
	 * 第三方应用
	 * - 获取访问用户身份
	 * - 使用code换取信息，用于用户点击app进入时，前端拿到code，后台再拿code去换取用户信息
	 * - https://developer.work.weixin.qq.com/document/path/91121
	 */
	async getUserInfoByCode(code: string) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/service/auth/getuserinfo3rd?suite_access_token=${this.suiteAccessToken}&code=${code}`;
		const res = await this.curl<WeWork.IGetSuiteUserInfoResponse>(url, {
			method: "GET",
			dataType: "json",
			contentType: "json",
			timeout: [30000, 30000],
		});
		if (res.data.errcode && res.data.errcode !== 0) {
			this.app.logger.error(`获取访问用户身份出错 %j`, res.data);
			throw new Error(res.data.errcode + (res.data.errmsg || ""));
		}
		return res.data;
	}
}
